<template>
  <div v-if="!props.data?.children || props.data?.children.length === 0" class="menu-item">
    <div class="menu-item__index"></div>
    <ACheckbox :value="props.data?.value" />
    <div class="menu-item__text">
      {{ props.data?.label }}
    </div>
  </div>
  <div
    v-else
    class="menu-item-node"
    :class="{ 'menu-item--expanded': expandedKeys[props.data?.value] }"
    :style="{ '--expanded-length': props.data?.children?.length * props.expandedKeys?.length }"
  >
    <div class="menu-item">
      <div class="menu-item__expand" :data-expand="props.data?.value">
        <CaretRightOutlined class="menu-item__expand-action" />
      </div>
      <ACheckbox :value="props.data?.value" />
      <div class="menu-item__text">
        {{ props.data?.label }}
      </div>
    </div>
    <div class="menu-item-children">
      <TreeSelectItem v-for="v in props.data?.children" :key="v?.value" :data="v" :expandedKeys="props.expandedKeys" />
    </div>
  </div>
</template>

<script setup>
import { CaretRightOutlined } from '@ant-design/icons-vue';
import { computed } from 'vue';

defineOptions({
  name: 'TreeSelectItem',
  inheritAttrs: false
});

const props = defineProps({
  data: { type: Object, default: () => ({}) },
  expandedKeys: { type: Array, default: () => [] }
});

const expandedKeys = computed(() => Object.fromEntries(Object.entries(props.expandedKeys).map(([a, b]) => [b, a])));
</script>

<style lang="scss" scoped>
.menu-item {
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  user-select: none;
  gap: 4px;

  .menu-item__expand {
    width: 24px;
    padding: 4px;
    text-align: center;
    border-radius: 4px;
    font-size: 12px;

    .menu-item__expand-action {
      transition: transform 0.3s;
    }
  }

  .menu-item__index {
    cursor: default;
    width: 24px;
    height: 24px;
  }

  .menu-item__text {
    flex-grow: 1;
    padding: 4px 8px;
    border-radius: 4px;

    &:hover {
      background-color: var(--hover-bg-color);
    }
  }
}

.menu-item-node {
  flex-basis: 100%;
  display: flex;
  flex-wrap: wrap;
  max-height: 32px;
  overflow: hidden;
  transition: max-height 0.4s ease;

  &.menu-item--expanded {
    max-height: calc((var(--expanded-length) + 1) * 32px);
  }

  &.menu-item--expanded > .menu-item .menu-item__expand-action {
    transform: rotate(90deg);
  }

  .menu-item-children {
    width: 100%;
    // max-height: 0px;
    padding-inline-start: 24px;
    display: flex;
    flex-wrap: wrap;
    overflow: hidden;
    transition: max-height 0.3s;
  }
}
</style>
